package com.lyf.gateway.config;

import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.client.LaxRedirectStrategy;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author yunfei.li
 * @date 2021/7/29 15:47
 */
@Configuration
public class RestTemplateConfig {
    @Bean("restTemplate")
    @LoadBalanced
    public RestTemplate restTemplate() {
        return getRestTemplate();
    }

    private RestTemplate getRestTemplate() {
        CloseableHttpClient httpClient
                = HttpClients.custom().disableCookieManagement()
                .setSSLHostnameVerifier(new NoopHostnameVerifier())
                .setMaxConnTotal(8192)
                .setMaxConnPerRoute(256)
                .setRedirectStrategy(new LaxRedirectStrategy())
                .build();

        HttpComponentsClientHttpRequestFactory requestFactory
                = new HttpComponentsClientHttpRequestFactory();
        requestFactory.setHttpClient(httpClient);

        // 连接时间
        requestFactory.setConnectionRequestTimeout(3000);
        requestFactory.setConnectTimeout(3000);
        requestFactory.setReadTimeout(15000);
        RestTemplate restTemplate = new RestTemplate(requestFactory);

        // 设置messageConverter
        setHttpMessageConverter(restTemplate);

        // 设置拦截器
        List<ClientHttpRequestInterceptor> interceptorList = new ArrayList<>();
//        interceptorList.add(new RestTemplateInterceptor());
        restTemplate.setInterceptors(interceptorList);

        return restTemplate;
    }

    private void setHttpMessageConverter(RestTemplate restTemplate) {
        MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
        mappingJackson2HttpMessageConverter.setSupportedMediaTypes(Arrays.asList(MediaType.ALL));
        restTemplate.getMessageConverters().add(mappingJackson2HttpMessageConverter);
        restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
    }
}
